const WebSocket = require('ws')
const config = require('config')
const jwt = require('jsonwebtoken')
const trash = require('@/utils/ini.util')
const { getLocationParams } = require('@/utils/common.util')

const clients = {}
const server = new WebSocket.Server({
  port: config.get('ws.port'),
  path: '/socket/message'
})

server.on('connection', (client, req) => {
  const id = getLocationParams(req.url, 'id')
  const token = getLocationParams(req.url, 'token')
  const authId = getLocationParams(req.url, 'authId')
  if (authId) {
    clients[authId] = client
    return client.send('连接建立成功')
  }
  if (!id || !token) {
    client.send(JSON.stringify({
      authenticate: false,
      code: '9999',
      message: '身份认证失败，连接断开'
    }))
    return client.close()
  }
  const decodedToken = jwt.verify(token, trash.jsonSecretkey)
  if (decodedToken.id !== id) {
    client.send(JSON.stringify({
      authenticate: false,
      code: '9999',
      message: '身份认证失败，连接断开'
    }))
    return client.close()
  }
  clients[id] = client
  client.send('连接建立成功')
  client.on('message', data => {
    const accept = data.toString().includes('{') ? JSON.parse(data.toString()) : data.toString()
    if (accept === 'ping') {
      client.send('pong')
    }
  })

  client.on('close', error => {
    console.log(error)
    console.log('与前端断开连接')
  })
})

module.exports = clients
